<template>
  <div class="tools-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><Tools /></el-icon>
            工具管理
          </h2>
          <p class="page-subtitle">管理和配置系统工具集，控制工具状态</p>
        </div>
        <div class="header-actions">
          <el-button 
            type="primary" 
            @click="initializeTools" 
            :loading="initializingTools"
            size="default"
            round
          >
            <el-icon><Refresh /></el-icon>
            初始化工具
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><Collection /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ pagination.total }}</div>
                <div class="stat-label">工具集总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon enabled">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getEnabledCategoriesCount() }}</div>
                <div class="stat-label">启用工具集</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon tools">
                <el-icon><Setting /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getTotalToolsCount() }}</div>
                <div class="stat-label">工具总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon active">
                <el-icon><Star /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getEnabledToolsCount() }}</div>
                <div class="stat-label">启用工具</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 工具集列表 -->
    <el-card class="main-card">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" @submit.prevent="searchCategories" inline>
          <el-form-item label="工具集名称">
            <el-input
              v-model="searchForm.category_name"
              placeholder="输入工具集名称"
              clearable
              style="width: 200px"
              @keyup.enter="searchCategories"
            />
          </el-form-item>
          <el-form-item label="工具代码">
            <el-input
              v-model="searchForm.category_code"
              placeholder="输入工具代码"
              clearable
              style="width: 150px"
              @keyup.enter="searchCategories"
            />
          </el-form-item>
          <el-form-item>
            <el-select 
              v-model="searchForm.is_enabled" 
              placeholder="状态筛选" 
              clearable
              style="width: 120px"
              @change="searchCategories"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchCategories">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 工具集表格 -->
      <el-table
        :data="categoriesList"
        v-loading="categoriesLoading"
        style="width: 100%"
        @row-click="selectCategory"
        :row-class-name="getRowClassName"
        empty-text="暂无工具集数据"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="category_name" label="工具集名称" min-width="180">
          <template #default="scope">
            <div class="category-name">
              <el-icon class="category-icon"><FolderOpened /></el-icon>
              <span class="name-text">{{ scope.row.category_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category_code" label="工具代码" width="150" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="info" size="small">{{ scope.row.category_code }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_enabled"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="(value: number) => toggleCategoryStatus(scope.row, value)"
              :loading="scope.row.statusLoading"
            />
          </template>
        </el-table-column>
        <el-table-column label="工具数量" width="120" align="center">
          <template #default="scope">
            <el-tag type="info" size="small">
              {{ scope.row.tools_count || 0 }} 个
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click.stop="viewCategoryTools(scope.row)"
              link
            >
              <el-icon><View /></el-icon>
              查看工具
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="searchCategories"
          @current-change="searchCategories"
          background
        />
      </div>
    </el-card>

    <!-- 工具详情面板 -->
    <el-card v-if="selectedCategory" class="tools-detail-card">
      <template #header>
        <div class="detail-header">
          <div class="detail-title">
            <el-icon class="detail-icon"><Tools /></el-icon>
            <span>{{ selectedCategory.category_name }} - 工具列表</span>
            <el-tag 
              :type="selectedCategory.is_enabled === 1 ? 'success' : 'danger'" 
              size="small"
              class="category-status-tag"
            >
              {{ selectedCategory.is_enabled === 1 ? '已启用' : '已禁用' }}
            </el-tag>
          </div>
          <div class="detail-info">
            <span class="tool-count">共 {{ toolsList.length }} 个工具</span>
          </div>
        </div>
      </template>

      <!-- 工具列表 -->
      <el-table
        :data="toolsList"
        v-loading="toolsLoading"
        style="width: 100%"
        empty-text="该工具集暂无工具"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="tool_name" label="工具名称" min-width="180">
          <template #default="scope">
            <div class="tool-name">
              <el-icon class="tool-icon"><Setting /></el-icon>
              <span class="name-text">{{ scope.row.tool_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_enabled"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="(value: boolean) => toggleToolStatus(scope.row, value)"
              :loading="scope.row.statusLoading"
            />
          </template>
        </el-table-column>
        <el-table-column label="人机交互" width="120" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.human_interactive_flag"
              :active-value="1"
              :inactive-value="0"
              active-color="#409eff"
              inactive-color="#dcdfe6"
              @change="(value: number) => toggleToolInteractive(scope.row, value)"
              :loading="scope.row.interactiveLoading"
            />
          </template>
        </el-table-column>
        <el-table-column label="参数数量" width="120" align="center">
          <template #default="scope">
            <el-tag type="info" size="small">
              {{ scope.row.parameters ? scope.row.parameters.length : 0 }} 个
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewToolParams(scope.row)"
              link
              v-if="scope.row.parameters && scope.row.parameters.length > 0"
            >
              <el-icon><Document /></el-icon>
              查看参数
            </el-button>
            <span v-else class="no-params">无参数</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 工具参数查看对话框 -->
    <el-dialog
      v-model="paramsDialogVisible"
      title="工具参数详情"
      width="800px"
      :before-close="closeParamsDialog"
    >
      <div class="params-dialog-content">
        <div class="params-header">
          <h4>{{ viewingTool?.tool_name }} - 参数配置</h4>
          <p class="params-description">{{ viewingTool?.description }}</p>
        </div>
        <el-table :data="viewingParams" style="width: 100%" border>
          <el-table-column prop="param_name" label="参数名称" width="150" />
          <el-table-column prop="param_type" label="类型" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getParamTypeColor(scope.row.param_type)">
                {{ scope.row.param_type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column prop="default_value" label="默认值" width="120">
            <template #default="scope">
              <code class="default-value">{{ scope.row.default_value || '-' }}</code>
            </template>
          </el-table-column>
          <el-table-column label="是否必需" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.is_required ? 'danger' : 'success'" size="small">
                {{ scope.row.is_required ? '必需' : '可选' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Tools, Search, Refresh, Collection, Check, Setting, Star, 
  FolderOpened, View, Document
} from '@element-plus/icons-vue'

// 导入API和类型定义
import { 
  toolsApi, 
  type ToolCategory,
  type Tool,
  type ToolParameter,
  type ToolCategorySearchParams
} from '@/api/tools'

// 响应式数据
const categoriesLoading = ref(false)
const toolsLoading = ref(false)
const initializingTools = ref(false)
const categoriesList = ref<ToolCategory[]>([])
const toolsList = ref<Tool[]>([])
const selectedCategory = ref<ToolCategory | null>(null)

// 搜索表单
const searchForm = reactive({
  category_name: '',
  category_code: '',
  is_enabled: null as number | null
})

// 分页
const pagination = reactive({
  page: 1,
  page_size: 10,
  total: 0
})

// 参数查看
const paramsDialogVisible = ref(false)
const viewingParams = ref<ToolParameter[]>([])
const viewingTool = ref<Tool | null>(null)

// 业务方法
const searchCategories = async () => {
  categoriesLoading.value = true
  try {
    const params: ToolCategorySearchParams = {
      page: pagination.page,
      page_size: pagination.page_size
    }
    
    if (searchForm.category_name) {
      params.category_name = searchForm.category_name
    }
    if (searchForm.category_code) {
      params.category_code = searchForm.category_code
    }
    if (searchForm.is_enabled !== null) {
      params.is_enabled = searchForm.is_enabled
    }

    const result = await toolsApi.getCategories(params)
    categoriesList.value = (result.items || []).map((item: ToolCategory) => ({
      ...item,
      statusLoading: false
    }))
    pagination.total = result.total || 0

    // 获取每个工具集的工具统计数据
    await loadToolsStatistics()
  } catch (error) {
    ElMessage.error('获取工具集列表失败')
    console.error(error)
  } finally {
    categoriesLoading.value = false
  }
}

const loadToolsStatistics = async () => {
  // 并行获取所有工具集的工具统计
  const promises = categoriesList.value.map(async (category) => {
    try {
      const toolsResult = await toolsApi.getToolsInCategory(category.id)
      const toolsCount = toolsResult.tools.length
      const enabledToolsCount = toolsResult.tools.filter((tool: any) => tool.is_enabled).length
      
      // 更新分类对象的统计信息
      category.tools_count = toolsCount
      category.enabled_tools_count = enabledToolsCount
    } catch (error) {
      console.error(`Failed to load tools for category ${category.id}:`, error)
    }
  })
  
  await Promise.all(promises)
}

const resetSearch = () => {
  searchForm.category_name = ''
  searchForm.category_code = ''
  searchForm.is_enabled = null
  pagination.page = 1
  searchCategories()
}

const selectCategory = async (row: ToolCategory) => {
  selectedCategory.value = row
  await loadCategoryTools(row.id)
}

const loadCategoryTools = async (categoryId: number) => {
  toolsLoading.value = true
  try {
    const result = await toolsApi.getToolsInCategory(categoryId)
    toolsList.value = (result.tools || []).map((tool: Tool) => ({
      ...tool,
      statusLoading: false
    }))
  } catch (error) {
    ElMessage.error('获取工具列表失败')
    console.error(error)
  } finally {
    toolsLoading.value = false
  }
}

const viewCategoryTools = async (row: ToolCategory) => {
  await selectCategory(row)
}

// 状态切换
const toggleCategoryStatus = async (row: ToolCategory, newStatus: number) => {
  row.statusLoading = true
  try {
    await toolsApi.updateCategoryStatus(row.id, { is_enabled: newStatus })
    ElMessage.success(`工具集${newStatus === 1 ? '启用' : '禁用'}成功`)
    // 更新本地状态
    row.is_enabled = newStatus
    // 如果是当前选中的工具集，也更新选中状态
    if (selectedCategory.value?.id === row.id) {
      selectedCategory.value.is_enabled = newStatus
    }
  } catch (error) {
    // 恢复原状态
    row.is_enabled = newStatus === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
    console.error(error)
  } finally {
    row.statusLoading = false
  }
}

const toggleToolStatus = async (tool: Tool, newStatus: boolean) => {
  if (!selectedCategory.value) return
  
  tool.statusLoading = true
  try {
    await toolsApi.updateToolStatus(selectedCategory.value.id, tool.tool_name, newStatus)
    ElMessage.success(`工具${newStatus ? '启用' : '禁用'}成功`)
    // 更新本地状态
    tool.is_enabled = newStatus
    
    // 更新当前工具集的统计数据
    const currentCategory = categoriesList.value.find(cat => cat.id === selectedCategory.value?.id)
    if (currentCategory) {
      const enabledCount = toolsList.value.filter(t => t.is_enabled).length
      currentCategory.enabled_tools_count = enabledCount
    }
  } catch (error) {
    // 恢复原状态
    tool.is_enabled = !newStatus
    ElMessage.error('状态更新失败')
    console.error(error)
  } finally {
    tool.statusLoading = false
  }
}

const toggleToolInteractive = async (tool: Tool, newFlag: number) => {
  if (!selectedCategory.value) return
  
  tool.interactiveLoading = true
  try {
    await toolsApi.updateToolInteractive(selectedCategory.value.id, tool.tool_name, newFlag)
    ElMessage.success(`工具交互${newFlag === 1 ? '启用' : '禁用'}成功`)
    // 更新本地状态
    tool.human_interactive_flag = newFlag
  } catch (error) {
    // 恢复原状态
    tool.human_interactive_flag = newFlag === 1 ? 0 : 1
    ElMessage.error('交互状态更新失败')
    console.error(error)
  } finally {
    tool.interactiveLoading = false
  }
}

// 参数查看
const viewToolParams = (tool: Tool) => {
  viewingTool.value = tool
  viewingParams.value = tool.parameters || []
  paramsDialogVisible.value = true
}

const closeParamsDialog = () => {
  paramsDialogVisible.value = false
  viewingTool.value = null
  viewingParams.value = []
}

// 工具初始化
const initializeTools = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要初始化工具到数据库吗？这将会从代码中加载所有工具定义。', 
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    initializingTools.value = true
    const result = await toolsApi.initializeAllTools()
    ElMessage.success(result.message)
    await searchCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('初始化失败')
      console.error(error)
    }
  } finally {
    initializingTools.value = false
  }
}

// 统计方法
const getEnabledCategoriesCount = () => {
  return categoriesList.value.filter(item => item.is_enabled === 1).length
}

const getTotalToolsCount = () => {
  return categoriesList.value.reduce((total, category) => {
    return total + (category.tools_count || 0)
  }, 0)
}

const getEnabledToolsCount = () => {
  return categoriesList.value.reduce((total, category) => {
    return total + (category.enabled_tools_count || 0)
  }, 0)
}

// 工具方法
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const getRowClassName = ({ row }: { row: ToolCategory }) => {
  return row.is_enabled === 0 ? 'disabled-row' : ''
}

const getParamTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    'string': 'success',
    'integer': 'primary',
    'float': 'warning',
    'boolean': 'info'
  }
  return colorMap[type] || 'info'
}

// 生命周期
onMounted(() => {
  searchCategories()
})
</script>

<style scoped>
.tools-management {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

/* 页面头部 */
.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  color: #409eff;
  font-size: 28px;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-icon.enabled {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.stat-icon.tools {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.stat-icon.active {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

/* 主卡片 */
.main-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  margin-bottom: 20px;
}

.search-section {
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

/* 表格样式 */
.category-name,
.tool-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-icon,
.tool-icon {
  color: #409eff;
  font-size: 16px;
}

.name-text {
  font-weight: 500;
  color: #303133;
}

.disabled-row {
  background-color: #fafafa;
  color: #c0c4cc;
}

.disabled-row .name-text {
  color: #c0c4cc;
}

.no-params {
  color: #c0c4cc;
  font-size: 12px;
}

/* 工具详情卡片 */
.tools-detail-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-icon {
  color: #409eff;
  font-size: 18px;
}

.category-status-tag {
  margin-left: 12px;
}

.detail-info {
  font-size: 14px;
  color: #909399;
}

.tool-count {
  background: #f4f4f5;
  padding: 4px 8px;
  border-radius: 4px;
}

/* 分页 */
.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 参数对话框 */
.params-dialog-content {
  padding: 16px 0;
}

.params-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.params-header h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.params-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.default-value {
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
}

/* 响应式 */
@media (max-width: 768px) {
  .tools-management {
    padding: 12px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .stats-cards .el-col {
    margin-bottom: 12px;
  }
}
</style> 